<template>
  <div class="login-container">
    <el-card class="login-card" shadow="never">
      <template #header>
        <div class="card-header">员工管理系统</div>
      </template>
      <el-form :model="loginForm" :rules="loginRules" ref="loginRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'

const router = useRouter()
const loginRef = ref(null)

const loginForm = reactive({
  username: 'admin',
  password: '123456'
})

const loginRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
})

const handleLogin = async () => {
  loginRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // json-server模拟登录：查找用户
        const res = await request.get('/users', { params: { username: loginForm.username, password: loginForm.password } })
        if (res.length > 0) {
          localStorage.setItem('token', 'mock-token')
          router.push('/users')
        } else {
          ElMessage.error('用户名或密码错误')
        }
      } catch (err) {
        ElMessage.error('登录失败')
      }
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.login-card {
  width: 400px;
}

.card-header {
  font-size: 20px;
  font-weight: bold;
  text-align: center;
}
</style>  